package com.example.Nurse_Notifier;


import android.net.DhcpInfo;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.util.Log;

public class WifiConfigurator {

    private WifiManager wifiManager;
    private final String NETWORK_SSID = "\"MAGENTA-VISITORS\"";
    private final String NET_PASSWORD = "\"sert-45-mab-998\"";
    private DhcpInfo dhcpInfo;

    private boolean isConnected = false;

    public WifiConfigurator(WifiManager wifiManager) {
        this.wifiManager = wifiManager;
    }

    public void turnOnWifi() {
        wifiManager.setWifiEnabled(true);
    }

    public void turnOffWifi() {
        wifiManager.setWifiEnabled(false);
    }

    public boolean checkWiFiState() {
        return wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED ||
                wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLING;
    }

    public void configureMulticast() {
        WifiManager.MulticastLock multicastLock = wifiManager.createMulticastLock("multi");
        multicastLock.setReferenceCounted(false);
        multicastLock.acquire();
    }

    public boolean connectToNet() {
        if (checkWiFiState()) {
            WifiConfiguration conf = new WifiConfiguration();
            String networkSSID = NETWORK_SSID;
            conf.SSID = networkSSID;
            conf.preSharedKey = NET_PASSWORD;
            conf.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            int res = wifiManager.addNetwork(conf);
            wifiManager.disconnect();
            wifiManager.enableNetwork(res, true);
            isConnected = wifiManager.reconnect();
            wifiManager.saveConfiguration();
            setDhcpInfo(wifiManager.getDhcpInfo());
            return isConnected;
        } else {
            Log.i("Error", "Wifi adapter is off");
            return false;
        }
    }

    public void setDhcpInfo(DhcpInfo dhcpInfo) {
        this.dhcpInfo = dhcpInfo;
    }
}
